package com.szh.mysobproject.ui.adapter


import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.szh.mysobproject.databinding.LikeMsgListItemBinding
import com.szh.mysobproject.model.msg.LikeMsg
import com.szh.mysobproject.util.setFixOnClickListener

class LikeMsgAdapter(private val adapterDelegate: AdapterDelegate) :
    PagingDataAdapter<LikeMsg.Content, LikeMsgAdapter.LikeMsgViewHolder>(LikeMsgCallBack()) {

    class LikeMsgCallBack : DiffUtil.ItemCallback<LikeMsg.Content>() {

        override fun areItemsTheSame(oldItem: LikeMsg.Content, newItem: LikeMsg.Content): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(
            oldItem: LikeMsg.Content,
            newItem: LikeMsg.Content
        ): Boolean {
            return oldItem == newItem
        }

    }

    inner class LikeMsgViewHolder(val binding: LikeMsgListItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onViewAttachedToWindow(holder: LikeMsgViewHolder) {
        super.onViewAttachedToWindow(holder)
        adapterDelegate.onViewAttachedToWindow(holder)
    }

    override fun onBindViewHolder(holder: LikeMsgViewHolder, position: Int) {
        val binding = holder.binding
        val itemView = holder.itemView
        val ivAvatar = binding.ivAvatar
        val cbNickName = binding.cbNickName
        val tvDesc = binding.tvDesc
        val tvReplyMsg = binding.tvReplyMsg
        val tvChildReplyMsg = binding.tvChildReplyMsg
        val context = itemView.context
        val item = getItem(position) ?: return
        itemView.setFixOnClickListener {
            adapterDelegate.onItemClick(it, position)
        }
        ivAvatar.loadAvatar(false, item.avatar)
        cbNickName.text = item.nickname
        tvDesc.text = item.timeText
        tvReplyMsg.height = 0
        tvChildReplyMsg.text = HtmlCompat.fromHtml(item.title, HtmlCompat.FROM_HTML_MODE_LEGACY)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LikeMsgViewHolder {
        val binding =
            LikeMsgListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return LikeMsgViewHolder(binding)
    }
}